package com.it.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.reggie.dao.DishDao;
import com.it.reggie.dao.DishFlavorDao;
import com.it.reggie.entity.Dish;
import com.it.reggie.dto.DishDto;
import com.it.reggie.entity.DishFlavor;
import com.it.reggie.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author:cyh
 * @data:2022/12/15 19:33
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements IDishService {
    @Autowired
    DishDao dishDao;

    @Autowired
    DishFlavorDao dishFlavorDao;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean saveDishWithFlavor(DishDto dishDto) {
        int insert = dishDao.insert(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        int insert1=0;
        if (flavors!=null&&flavors.size()>0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDto.getId());
                insert1 = dishFlavorDao.insert(flavor);
            }
        }
        return insert > 0 && insert1 > 0;
    }

    @Override
    public DishDto queryById(Long id) {
        Dish dish = dishDao.selectById(id);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorDao.selectList(wrapper);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean updateWithFlavor(DishDto dishDto) {
        //修改dish表
        dishDao.updateById(dishDto);
        //删除dishflavor表的口味数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorDao.delete(wrapper);
        //向口味表中添加信息
        for (DishFlavor dishFlavor : dishDto.getFlavors()) {
            dishFlavor.setDishId(dishDto.getId());
            dishFlavorDao.insert(dishFlavor);
        }

        return true;
    }
}
